<?php namespace App\Http\Controllers\Api;

use App\Design;
use App\DesignBodyImg;
use App\DesignResult;
use App\DesignResultImg;
use App\Files;
use App\Goods;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Http\Services\Tools;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatModelMsg;
use App\Http\Services\YunPian;
use App\Images;
use App\Material;
use App\OrderAddress;
use App\OrderItem;
use App\Orders;
use App\RedPacket;
use App\RewardFollow;
use App\RewardRules;
use App\Support;
use App\User;
use App\UserAddress;
use App\Userinfo;
use EasyWeChat\Payment\Order;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Log;

class DesignController extends Controller
{
    public function getDesignTemplate(Request $request){
        $gid   = $request->get('gid');
        $face  = !is_null($request->get('face')) ? $request->get('face') : 0;
        $color = !is_null($request->get('color')) ? $request->get('color') : '#ffffff';

        /** @var Goods $thatGood */
        $thatGood = Goods::whereId($gid)->whereIsshop(1)->first();
        if(!$thatGood)
            return response()->json(['level'=>'error','message'=>'该商品不存在或未上架','data'=>'']);

        $thatGoodDesign = Design::whereGId($gid)->whereFace($face)->whereColorSpace($color)->first();
        if(!$thatGoodDesign)
            return response()->json(['level'=>'error','message'=>'当前商品不存在所选元素面板','data'=>'']);

        $thatGoodDesign->img_url = FileManager::getAliOssFile($thatGoodDesign->img_id);

        return response()->json(['level'=>'success','message'=>'获取设计样版','data'=>$thatGoodDesign]);
    }

    public function getMaterial(Request $request){
        $classifyType = !is_null($request->get('type')) ? $request->get('type') : 'zh';

        $materials = null;
        $heng = array();
        $shu  = array();
        $materials = null;
        switch ($classifyType){
            case 'zh':
                $materials = Material::whereClassifyId(0)->orderBy("created_at","desc")->orderBy("id","asc")->get();
                break;
            case 'en':
                $materials = Material::whereClassifyId(1)->orderBy("created_at","desc")->orderBy("id","asc")->get();
                break;
            case 'img':
                $materials = Material::whereClassifyId(2)->orderBy("created_at","desc")->orderBy("id","asc")->get();
                break;
        }

        $blankImg['img_url']       = '';
        $blankImg['img_thumb_url'] = url('images/blank_img.png');
        $blankImg['img_id'] = 0;
        array_push($heng,$blankImg);

        if(count($materials) > 0){
            foreach ($materials as $material){
                if(is_null($material->type)){
                    /** @var Material $material */
                    $images = Images::whereId($material->thumb_img_id)->first();
                    if($images) {
                        /** @var Files $imageFile */
                        $imageFile = $images->files;
                        $imgHeight = Image::make($imageFile->getContent())->height();
                        $imgWidth  = Image::make($imageFile->getContent())->width();

                        if($imgWidth >= $imgHeight){
                            $material->type = "heng";
                            $material->save();

                            $imgInfo['img_url']       = FileManager::getAliOssFile($material->img_id);
                            $imgInfo['img_thumb_url'] = FileManager::getAliOssFile($material->thumb_img_id);;
                            $imgInfo['img_id']        = $material->img_id;
                            array_push($heng,$imgInfo);
                        }else{
                            $material->type = "shu";
                            $material->save();

                            $imgInfo['img_url']       = FileManager::getAliOssFile($material->img_id);
                            $imgInfo['img_thumb_url'] = FileManager::getAliOssFile($material->thumb_img_id);
                            $imgInfo['img_id']        = $material->img_id;
                            array_push($shu,$imgInfo);
                        }
                    }
                }else{
                    if($material->type == "heng"){
                        $imgInfo['img_url']       = FileManager::getAliOssFile($material->img_id);
                        $imgInfo['img_thumb_url'] = FileManager::getAliOssFile($material->thumb_img_id);;
                        $imgInfo['img_id']        = $material->img_id;
                        array_push($heng,$imgInfo);
                    }elseif ($material->type == "shu"){
                        $imgInfo['img_url']       = FileManager::getAliOssFile($material->img_id);
                        $imgInfo['img_thumb_url'] = FileManager::getAliOssFile($material->thumb_img_id);
                        $imgInfo['img_id']        = $material->img_id;
                        array_push($shu,$imgInfo);
                    }
                }
            }
        }

        $result['heng'] = $heng;
        $result['shu']  = $shu;

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$result]);
    }

    public function getColorImgList(){
        $allColor = Design::whereFace(0)->get();

        $colorImgs = array();
        if(count($allColor) > 0){
            foreach ($allColor as $color){
                /** @var Design $color */
                $colorImg['color_space'] = $color->color_space;
                $colorImg['color_img_url'] = FileManager::getAliOssFile($color->thumb_img_id);

                array_push($colorImgs,$colorImg);
            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$colorImgs]);
    }

    public function buildCompositeImg(Request $request){
        $color        = $request->get('color');
        $gid          = $request->get('gid');
        $materialUp   = !is_null($request->get('material_up_id')) ? $request->get('material_up_id') : 0;
        $materialDown = !is_null($request->get('material_down_id')) ? $request->get('material_down_id') : 0;

        /** @var Goods $thatGoods */
        $thatGoods = Goods::whereId($gid)->first();
        if(!$thatGoods)
            return response()->json(['level'=>'error','message'=>'商品不存在','data'=>'']);

        /** @var Design $thatFaceUpDesign */
        $thatFaceUpDesign = Design::whereGId($gid)->whereColorSpace($color)->whereFace(0)->first();
        if(!$thatFaceUpDesign){
            return response()->json(['level'=>'error','message'=>'暂无此设计样版','data'=>'']);
        }

        /** @var Design $thatFaceDownDesign */
        $thatFaceDownDesign = Design::whereGId($gid)->whereColorSpace($color)->whereFace(1)->first();
        if(!$thatFaceDownDesign){
            return response()->json(['level'=>'error','message'=>'暂无此设计样版','data'=>'']);
        }

        $bodyFaceUpImgs = DesignBodyImg::whereDId($thatFaceUpDesign->id)->get();
        $bodyFaceDownImgs = DesignBodyImg::whereDId($thatFaceDownDesign->id)->get();

        $thatMaterialUp   = Material::whereImgId($materialUp)->first();
        $thatMaterialDown = Material::whereImgId($materialDown)->first();

        $key = Tools::randLetter(8);
        while (true){
            $thatKey = DesignResult::whereKey($key)->first();
            if(!$thatKey){
                break;
            }else{
                $key = Tools::randLetter(8);
            }
        }

        $user = UserManager::isLogin($request);

        $newDesign = new DesignResult();
        $newDesign->g_id    = $gid;
        $newDesign->color   = $color;
        $newDesign->price   = $thatGoods->s_price;
        $newDesign->key     = $key;
        $newDesign->user_id = $user ? $user->id : 0;
        $newDesign->save();

        $showImgs = array();
        if(count($bodyFaceUpImgs) > 0){
            $newDesign->front_img_id = $thatMaterialUp ? $thatMaterialUp->img_id : 0;
            $newDesign->front_mid    = $thatMaterialUp ? $thatMaterialUp->id : 0;
            $newDesign->price        = $thatMaterialUp ? $newDesign->price +  $thatMaterialUp->price: $newDesign->price;
            $newDesign->save();
            foreach ($bodyFaceUpImgs as $bodyFaceUpImg){
                /** @var DesignBodyImg $bodyFaceUpImg */

                //模特展示图
                $thatModelImg = Images::whereId($bodyFaceUpImg->img_id)->first();
                if(!$thatModelImg)
                    return response()->json(['level'=>'error','message'=>'模特图不存在','data'=>'']);
                /** @var Files $thatModelImgFile */
                $thatModelImgFile = $thatModelImg->files;
                if(!$thatModelImgFile)
                    return response()->json(['level'=>'error','message'=>'文件不存在','data'=>'']);
                $modelFileContent = $thatModelImgFile->getContent();
                $modelImg    = Image::make($modelFileContent);

                $imageModel = false;
                if($thatMaterialUp){
                    $imgMaterial = Images::whereId($thatMaterialUp->img_id)->first();
                    if(!$imgMaterial)
                        return response()->json(['level'=>'error','message'=>'素材图不存在','data'=>'']);

                    /** @var Files $imgMaterialFile */
                    $thatMaterialFile = $imgMaterial->files;
                    if(!$thatMaterialFile)
                        return response()->json(['level'=>'error','message'=>'文件不存在','data'=>'']);

                    $thatMaterialContent = $thatMaterialFile->getContent();

                    $watermark = Image::make($thatMaterialContent);
                    $watermark->widen(230);
                    $modelImg->insert($watermark, 'top',195,344)->encode($thatModelImgFile->file_ext);
                    /** @var Files $fileResult */
                    $fileResult = FileManager::saveFileByFileContent($modelImg->encoded, $thatModelImgFile->file_name . '-new' . $thatModelImgFile->file_type, $modelImg->mime());

                    $imageModel = new Images();
                    $imageModel->files()->associate($fileResult);
                    $imageModel->img_type = $thatModelImgFile->file_type;
                    $imageModel->img_name = $thatModelImgFile->file_name.'-new';
                    $imageModel->save();
                }

                $aa = \Storage::disk('oss')->get('main/png-24.png');
                $thumbTempleImg = Image::make($aa);
                $modelImg->widen(85);
                $thumbTempleImg->insert($modelImg,'bottom',0,0)->encode($thatModelImgFile->file_ext);
                /** @var Files $fileThumb */
                $fileThumb = FileManager::saveFileByFileContent($thumbTempleImg->encoded, $thatModelImgFile->file_name . '-new-thumb' . $thatModelImgFile->file_type, $thumbTempleImg->mime());

                $imageThumbModel = new Images();
                $imageThumbModel->files()->associate($fileThumb);
                $imageThumbModel->img_type = $thatModelImgFile->file_type;
                $imageThumbModel->img_name = $thatModelImgFile->file_name.'-new-thumb';
                $imageThumbModel->save();

                $resultThumnImg = new DesignResultImg();
                $resultThumnImg->img_id       =  $imageModel ? $imageModel->id : $bodyFaceUpImg->img_id;
                $resultThumnImg->thumb_img_id = $imageThumbModel->id;
                $resultThumnImg->dr_id        = $newDesign->id;
                $resultThumnImg->sex          = $bodyFaceUpImg->sex;
                $resultThumnImg->face         = $bodyFaceUpImg->face;
                $resultThumnImg->save();
            }
        }

        if(count($bodyFaceDownImgs) > 0) {
            $newDesign->back_img_id = $thatMaterialDown ? $thatMaterialDown->img_id : 0;
            $newDesign->back_mid = $thatMaterialDown ? $thatMaterialDown->id : 0;
            $newDesign->price = $thatMaterialDown ? $newDesign->price + $thatMaterialDown->price : $newDesign->price;
            $newDesign->save();

            foreach ($bodyFaceDownImgs as $bodyFaceDownImg) {
                /** @var DesignBodyImg $bodyFaceDownImg */

                //模特展示图
                $thatModelImg = Images::whereId($bodyFaceDownImg->img_id)->first();
                if (!$thatModelImg)
                    return response()->json(['level' => 'error', 'message' => '模特图不存在', 'data' => '']);
                /** @var Files $thatModelImgFile */
                $thatModelImgFile = $thatModelImg->files;
                if (!$thatModelImgFile)
                    return response()->json(['level' => 'error', 'message' => '文件不存在', 'data' => '']);
                $modelFileContent = $thatModelImgFile->getContent();
                $modelImg = Image::make($modelFileContent);

                $imageModel = false;
                if ($thatMaterialDown) {

                    $imgMaterial = Images::whereId($thatMaterialDown->img_id)->first();
                    if (!$imgMaterial)
                        return response()->json(['level' => 'error', 'message' => '素材图不存在', 'data' => '']);

                    /** @var Files $imgMaterialFile */
                    $thatMaterialFile = $imgMaterial->files;
                    if (!$thatMaterialFile)
                        return response()->json(['level' => 'error', 'message' => '文件不存在', 'data' => '']);

                    $thatMaterialContent = $thatMaterialFile->getContent();

                    $watermark = Image::make($thatMaterialContent);
                    $watermark->widen(230);
                    $modelImg->insert($watermark, 'top', 195, 320)->encode($thatModelImgFile->file_ext);
                    /** @var Files $fileResult */
                    $fileResult = FileManager::saveFileByFileContent($modelImg->encoded, $thatModelImgFile->file_name . '-new' . $thatModelImgFile->file_type, $modelImg->mime());

                    $imageModel = new Images();
                    $imageModel->files()->associate($fileResult);
                    $imageModel->img_type = $thatModelImgFile->file_type;
                    $imageModel->img_name = $thatModelImgFile->file_name . '-new';
                    $imageModel->save();
                }

                $aa = \Storage::disk('oss')->get('main/png-24.png');
                $thumbTempleImg = Image::make($aa);
                $modelImg->widen(85);
                $thumbTempleImg->insert($modelImg, 'bottom', 0, 0)->encode($thatModelImgFile->file_ext);
                /** @var Files $fileThumb */
                $fileThumb = FileManager::saveFileByFileContent($thumbTempleImg->encoded, $thatModelImgFile->file_name . '-new-thumb' . $thatModelImgFile->file_type, $thumbTempleImg->mime());

                $imageThumbModel = new Images();
                $imageThumbModel->files()->associate($fileThumb);
                $imageThumbModel->img_type = $thatModelImgFile->file_type;
                $imageThumbModel->img_name = $thatModelImgFile->file_name . '-new-thumb';
                $imageThumbModel->save();

                $resultThumnImg = new DesignResultImg();
                $resultThumnImg->img_id = $imageModel ? $imageModel->id : $bodyFaceDownImg->img_id;
                $resultThumnImg->thumb_img_id = $imageThumbModel->id;
                $resultThumnImg->dr_id = $newDesign->id;
                $resultThumnImg->sex = $bodyFaceDownImg->sex;
                $resultThumnImg->face = $bodyFaceDownImg->face;
                $resultThumnImg->save();
            }
        }


        if($thatMaterialUp){
            $tShirtImage = self::saveTShirtEffect($thatFaceUpDesign,$thatMaterialUp);
            if($tShirtImage){
                $newDesign->effect_front_id = $tShirtImage->id;
                $newDesign->save();
            }else{
                $newDesign->effect_front_id = $thatFaceUpDesign->id;
                $newDesign->save();
            }

        }else{
            $newDesign->effect_front_id = $thatFaceUpDesign->id;
            $newDesign->save();
        }

        $newDesign->show_imgs = $showImgs;

        return response()->json(['level'=>'success','message'=>'完成','data'=>$newDesign->key]);
    }

    public function getBuildDesignByCode(Request $request){
        $code = $request->get('code');

        $thatBuild = DesignResult::whereKey($code)->first();
        if(!$thatBuild)
            return response()->json(['level'=>'error','message'=>'设计不存在','data'=>'']);

        $thatBuildInfos = DesignResultImg::whereDrId($thatBuild->id)->get();
        if(!$thatBuildInfos)
            return response()->json(['level'=>'error','message'=>'缩略图不存在','data'=>'']);

        $thumbImgs = array();
        foreach ($thatBuildInfos as $thatBuildInfo){
            /** @var DesignResultImg $thatBuildInfo */
            $info['img_url'] = FileManager::getAliOssFile($thatBuildInfo->img_id);
            $info['thumb_img_url'] = FileManager::getAliOssFile($thatBuildInfo->thumb_img_id);
            array_push($thumbImgs,$info);
        }

        $thatBuild->imgs = $thumbImgs;

        $upPrice = 0;
        /** @var Material $thatUpMaterial */
        $thatUpMaterial = Material::whereId($thatBuild->front_mid)->first();
        if($thatUpMaterial){
            $upPrice = $thatUpMaterial->price;
        }

        $downPrice = 0;
        /** @var Material $thatDownMaterial */
        $thatDownMaterial = Material::whereId($thatBuild->back_mid)->first();
        if($thatDownMaterial){
            $downPrice = $thatDownMaterial->price;
        }

        /** @var Goods $thatGoods */
        $thatGoods = Goods::whereId($thatBuild->g_id)->first();

        $thatBuild->up_price      = $upPrice;
        $thatBuild->down_price    = $downPrice;
        $thatBuild->clothes_price = $thatGoods ? $thatGoods->s_price : 0;

//        $designBody = DesignResultImg::whereDrId($thatBuild->id)->whereSex(1)->whereFace("front")->first();
        //显示图
        if($thatBuild->effect_front_id != 0){
            $thatBuild->goods_img_url = FileManager::getAliOssFile($thatBuild->effect_front_id);
        }else{
            $thatBuild->goods_img_url = FileManager::getAliOssFile(1);
        }

        if(self::isActiveAction()){
            $thatBuild->is_action = 1;
        }else{
            $thatBuild->is_action = 0;
        }

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$thatBuild]);
    }

    public function buildOrder(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'请先登录','data'=>'no_login']);

        $code        = $request->get('code');
        $size        = $request->get('size');
        $addressArea = $request->get('address_area');
        $addressInfo = $request->get('address_info');
        $phone       = $request->get('phone');
        $consignee   = $request->get('consignee');

        /** @var DesignResult $thatDesignResult */
        $thatDesignResult = DesignResult::whereKey($code)->first();
        if(!$thatDesignResult)
            return response()->json(['level'=>'error','message'=>'当前设计不存在','data'=>'']);

        if(!is_array($size))
            return response()->json(['level'=>'error','message'=>'size的数据格式错误，应为数组','data'=>'']);

        if(count($size) == 0){
            return response()->json(['level'=>'error','message'=>'至少选择一个码数哦！','data'=>'']);
        }

        if($thatDesignResult->user_id == 0){
            $thatDesignResult->user_id = $user->id;
            $thatDesignResult->save();
        }

        $addressInfoArr = explode(' ',$addressArea);

        $newOrder = new Orders();
        $newOrder->user_id   = $user->id;
        $newOrder->order_num = Tools::makeBillNum();
        $newOrder->type      = 'design';
        $newOrder->note      = $code;
        $newOrder->save();

        if(count($size) > 0){
            $num = 0;
            foreach ($size as $thatSize){
                $newOrderItem =new OrderItem();
                $newOrderItem->gid = $thatDesignResult->id;
                $newOrderItem->size = $thatSize;
                $newOrderItem->price = $thatDesignResult->price;
                $newOrderItem->type  = 'design';
                $newOrderItem->order_id = $newOrder->id;
                $newOrderItem->order_num = $newOrder->order_num;
                $newOrderItem->design_key = $code;
                $newOrderItem->save();

                $num++;
            }

            $newOrder->s_amount = round((float)$thatDesignResult->price * $num,2);
            $newOrder->num = $num;
            $newOrder->save();
        }

        $newOrderAddress = new OrderAddress();
        $newOrderAddress->user_id   = $user->id;
        $newOrderAddress->consignee = $consignee;
        $newOrderAddress->province  = $addressInfoArr[0];
        $newOrderAddress->city      = $addressInfoArr[1];
        $newOrderAddress->area      = $addressInfoArr[2];
        $newOrderAddress->add_detail = $addressInfo;
        $newOrderAddress->telephone  = $phone;
        $newOrderAddress->save();

        $newOrder->address_id = $newOrderAddress->id;
        $newOrder->save();

        /** @var Userinfo $thatUserInfo */
        $thatUserInfo = Userinfo::whereUserId($user->id)->first();
        if($thatUserInfo && is_null($thatUserInfo->realname)){
            $thatUserInfo->realname = $consignee;
            $thatUserInfo->save();
        }

        $thatUserAddress = UserAddress::whereUserId($user->id)->whereIsDefault(1)->first();
        if(!$thatUserAddress){
            $thatUserAddress = new UserAddress();
            $thatUserAddress->user_id     = $user->id;
            $thatUserAddress->consignee   = $consignee;
            $thatUserAddress->province    = $addressInfoArr[0];
            $thatUserAddress->city        = $addressInfoArr[1];
            $thatUserAddress->area        = $addressInfoArr[2];
            $thatUserAddress->add_detail  = $addressInfo;
            $thatUserAddress->mobilephone = $phone;
            $thatUserAddress->is_default  = 1;
            $thatUserAddress->save();
        }

        $result = null;
        if(self::isActiveAction()){
            $newOrder->pay_type = "free";
            $newOrder->save();

            $result['pay_type'] = "free";
        }else{
            $newOrder->pay_type = "wxpay";
            $newOrder->save();
            
            $result['pay_type'] = "cash";
        }

        $result['order_num'] = $newOrder->order_num;

        //发送微信模版消息
        WechatModelMsg::sendMsgToManager("orn9vwAJuQMaGBV5gXHgkebTHP-0",$newOrder->order_num);
        WechatModelMsg::sendMsgToManager("orn9vwBZKVA94mZTzR2nhbTI4Mbs",$newOrder->order_num);

        return response()->json(['level'=>'success','message'=>'下单成功','data'=>$result]);
    }

    public function supportDesign(Request $request){
        $code = $request->get('code');

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'请先登录','data'=>'no_login']);

        /** @var DesignResult $thatDesignResult */
        $thatDesignResult = DesignResult::whereKey($code)->first();
        if(!$thatDesignResult)
            return response()->json(['level'=>'error','message'=>'当前设计不存在','data'=>'']);

        /** @var Support $hasSupport */
        $hasSupport = Support::whereSUserId($user->id)->whereDrId($thatDesignResult->id)->first();
        if($hasSupport)
            return response()->json(['level'=>'error','message'=>'您已经支持过了呦！','data'=>'']);

        if(!self::isActiveAction())
            return response()->json(['level'=>'error','message'=>'活动已结束咯！感谢您的支持','data'=>'']);

        $newSupport = new Support();
        $newSupport->user_id = $thatDesignResult->user_id;
        $newSupport->s_user_id = $user->id;
        $newSupport->dr_id     = $thatDesignResult->id;
        $newSupport->save();

        if($thatDesignResult->support_num < 20){
            $thatDesignResult->support_num = (int)$thatDesignResult->support_num + 1;
            $thatDesignResult->save();
        }


//        /** @var $thatOrderItem $thatOrderItem */
//        $thatOrderItem = OrderItem::whereDesignKey($code)->whereType("design")->first();
//        if(!$thatOrderItem){
//            Log::error('red_packet==>订单未付款');
//            return response()->json(['level'=>'success','message'=>'感谢您的支持！','data'=>'']);
//        }

//        /** @var Orders $thatOrder */
//        $thatOrder = Orders::whereId($thatOrderItem->order_id)->first();
//        if(!$thatOrder || ($thatOrder && $thatOrder->ispay == 0)){
//            Log::error('red_packet==>订单未付款');
//            return response()->json(['level'=>'success','message'=>'感谢您的支持！','data'=>'']);
//        }

        //发放返利
        if($thatDesignResult->support_num >= 20){
            $thatOrderNum = Orders::wherePayType("free")->whereIspay(1)->count();
            if((int)$thatOrderNum < 10){
                /** @var Orders $thatOrder */
                $thatOrder = Orders::whereUserId($thatDesignResult->user_id)->whereIspay(0)->whereNote($code)->wherePayType("free")->first();
                if(!$thatOrder){
                    Log::error('active==>订单不存在 || code='.$code);
                }

                $thatOrder->ispay = 1;
                $thatOrder->paytime = date("Y-m-d H:i:s",time());
                $thatOrder->save();

                //发短信
                /** @var OrderAddress $thatOrderAddress */
                $thatOrderAddress = OrderAddress::whereId($thatOrder->address_id)->first();
                if($thatOrderAddress){
                    if(!is_null($thatOrderAddress->telephone)){
                        $sendSms = new YunPian();
                        $sendSms->sendSupperReachSms($thatOrderAddress->telephone,"20");
                    }
                }

                WechatModelMsg::sendMsgToManager("orn9vwAJuQMaGBV5gXHgkebTHP-0",$thatOrder->order_num);
                WechatModelMsg::sendMsgToManager("orn9vwBZKVA94mZTzR2nhbTI4Mbs",$thatOrder->order_num);

            }else{
                Log::error('active==>名额已满 || code='.$code);
            }
        }
//        if($thatDesignResult->support_num == 20 && $thatDesignResult->cashback <= 0){
//            $allRewardFollows = RewardFollow::whereIsUse(0)->whereStatus(1)->get();
//            if(count($allRewardFollows) > 0){
//                $followArr = array();
//                foreach ($allRewardFollows as $allRewardFollow){
//                    array_push($followArr,$allRewardFollow->id);
//                }
//                $allRewardFollowCount = count($followArr);
//                $randId = rand(0,$allRewardFollowCount-1);
//                /** @var RewardFollow $thatRewardFollow */
//                $thatRewardFollow = RewardFollow::whereId($followArr[$randId])->whereIsUse(0)->whereStatus(1)->first();
//                if($thatRewardFollow){
//                    /** @var RewardRules $thatRewardRules */
//                    $thatRewardRules = RewardRules::whereId($thatRewardFollow->rr_id)->whereStatus(1)->where('num','>',0)->first();
//                    if($thatRewardRules && (strtotime($thatRewardRules->start_time) < time() && strtotime($thatRewardRules->end_time) > time())){
//                        $sendAmount = round((float)$thatDesignResult->price * (float)$thatRewardRules->ratio,2);
//
//                        $thatReceiveUser = User::whereId($thatDesignResult->user_id)->first();
//                        if($thatReceiveUser) {
//                            $newRedPacket = new RedPacket();
//                            $newRedPacket->user_id = $thatReceiveUser->id;
//                            $newRedPacket->amount = $sendAmount;
//                            $newRedPacket->save();
//
//                            $sendResult = WechatController::sendRedPackage($thatReceiveUser->openid,$sendAmount);
//                            if($sendResult->result_code == 'SUCCESS'){
//                                $thatRewardFollow->is_use = 1;
//                                $thatRewardFollow->save();
//
//                                $thatRewardRules->num = (int)$thatRewardRules->num - 1;
//                                $thatRewardRules->save();
//
//                                $thatDesignResult->cashback = $sendAmount;
//                                $thatDesignResult->save();
//
//                                $newRedPacket->status = 1;
//                                $newRedPacket->save();
//
//                            }else{
//                                Log::error('red_packet==>'.$sendResult->err_code_des);
//                            }
//                        }else{
//                            Log::error('red_packet==>接收人不存在');
//                        }
//
//                    }else{
//                        Log::error('red_packet==>不符合规则');
//                    }
//                }else{
//                    Log::error('red_packet==>不存在该抽奖号');
//                }
//            }else{
//                Log::error('red_packet==>剩余排队人数不存在');
//            }
//
//        }else{
//            Log::error('red_packet==>支持人数超额');
//        }

        return response()->json(['level'=>'success','message'=>'感谢您的支持！','data'=>$thatDesignResult->support_num]);
    }

    public function getSupportNum(Request $request){
        $code = $request->get('code');

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'请先登录','data'=>'no_login']);

        /** @var DesignResult $thatDesignResult */
        $thatDesignResult = DesignResult::whereKey($code)->first();

        if(!$thatDesignResult)
            return response()->json(['level'=>'error','message'=>'code值无效！','data'=>'']);

        $thatUserInfo = Userinfo::whereUserId($thatDesignResult->user_id)->first();

        if(!$thatUserInfo){
            return response()->json(['level'=>'error','message'=>'该用户不存在！','data'=>'']);
        }

        $result['support_num'] = $thatDesignResult->support_num;
        $result['nickname']    = $thatUserInfo->nickname;

        if($user->id == $thatDesignResult->user_id){
            $result['is_oneself'] = 1;
        }else{
            $result['is_oneself'] = 0;
        }

        return response()->json(['level'=>'success','message'=>'获取成功！','data'=>$result]);
    }

    public function buildShareImage(Request $request){
        $code = $request->get('code');
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'请先登录','data'=>'no_login']);

        /** @var DesignResult $thatDesignResult */
        $thatDesignResult = DesignResult::whereKey($code)->first();
        if(!$thatDesignResult)
            return response()->json(['level'=>'error','message'=>'当前设计不存在','data'=>'']);

        if($thatDesignResult->share_img_id != 0 && $thatDesignResult->share_img_girl_id != 0){
            $imgUrl = FileManager::getLocalFile($thatDesignResult->share_img_id);
            $imgInfo['boy']['img_id'] = $thatDesignResult->share_img_id;
            $imgInfo['boy']['img_url'] = $imgUrl;

            $imgGirlUrl = FileManager::getLocalFile($thatDesignResult->share_img_girl_id);
            $imgInfo['girl']['img_id'] = $thatDesignResult->share_img_girl_id;
            $imgInfo['girl']['img_url'] = $imgGirlUrl;

            return response()->json(['level'=>'success','message'=>'获取分享图片成功','data'=>$imgInfo]);
        }

        /** @var Userinfo $userinfo */
        $userinfo = Userinfo::whereUserId($user->id)->first();
        if(!$userinfo)
            return response()->json(['level'=>'error','message'=>'用户不存在','data'=>'']);

        $thatDesignResultManImg = DesignResultImg::whereDrId($thatDesignResult->id)->whereSex(1)->whereFace('front')->first();

        $imgInfo = null;
        if($thatDesignResultManImg){
            $designImg = Images::whereId($thatDesignResultManImg->img_id)->first();
            if(!$designImg)
                return response()->json(['level'=>'error','message'=>'设计图不存在','data'=>'']);

            /** @var Files $designImgFile */
            $designImgFile = $designImg->files;

            $designImgInfo = Image::make($designImgFile->getContent());
            $designImgInfo->widen(420);

            //生成分享图片
            $backgroundImg = \Storage::disk('oss')->get('main/share.png');
            $backgroundImgInfo = Image::make($backgroundImg);

            $client   = new \GuzzleHttp\Client();
            $response = $client->get(route('Api.Upload.qrcode').'?code='.$code."&sex=1");
            $content  = $response->getBody()->getContents();
            $qrcodeImgInfo = Image::make($content);

            $qrcodeImgInfo->widen(86);
            $backgroundImgInfo->insert($qrcodeImgInfo, 'bottom-right',18,18)->encode("image/jpeg");
            $backgroundImgInfo->insert($designImgInfo, 'bottom',142,0)->encode("image/jpeg");
            /** @var Files $fileResult */
            $fileResult = FileManager::saveFileByFileContent($backgroundImgInfo->encoded, "qrcode-share.jpg", "image/jpeg","local");

            $imageThumbModel = new Images();
            $imageThumbModel->files()->associate($fileResult);
            $imageThumbModel->img_type = ".jpg";
            $imageThumbModel->img_name = "qrcode-share.jpg";
            $imageThumbModel->save();

            $thatDesignResult->share_img_id = $imageThumbModel->id;
            $thatDesignResult->save();

            $shareImgUrl = FileManager::getLocalFile($imageThumbModel->id);

            $imgInfo['boy']["img_url"] = $shareImgUrl;
            $imgInfo['boy']['img_id']  = $imageThumbModel->id;
        }


        //女生分享图
        $imgGirlInfo = array();
        $thatDesignResultGirlImg = DesignResultImg::whereDrId($thatDesignResult->id)->whereSex(2)->whereFace('front')->first();
        if($thatDesignResultGirlImg){
            $designImg = Images::whereId($thatDesignResultGirlImg->img_id)->first();
            if(!$designImg)
                return response()->json(['level'=>'error','message'=>'设计图不存在','data'=>'']);

            /** @var Files $designImgFile */
            $designImgFile = $designImg->files;

            $designImgInfo = Image::make($designImgFile->getContent());
            $designImgInfo->widen(420);

            //生成分享图片
            $backgroundImg = \Storage::disk('oss')->get('main/share.png');
            $backgroundImgInfo = Image::make($backgroundImg);

            $client   = new \GuzzleHttp\Client();
            $response = $client->get(route('Api.Upload.qrcode').'?code='.$code."&sex=2");
            $content  = $response->getBody()->getContents();
            $qrcodeImgInfo = Image::make($content);

            $qrcodeImgInfo->widen(86);
            $backgroundImgInfo->insert($qrcodeImgInfo, 'bottom-right',18,18)->encode("image/jpeg");
            $backgroundImgInfo->insert($designImgInfo, 'bottom',142,0)->encode("image/jpeg");
            /** @var Files $fileResult */
            $fileResult = FileManager::saveFileByFileContent($backgroundImgInfo->encoded, "qrcode-share.jpg", "image/jpeg","local");

            $imageThumbModel = new Images();
            $imageThumbModel->files()->associate($fileResult);
            $imageThumbModel->img_type = ".jpg";
            $imageThumbModel->img_name = "qrcode-share.jpg";
            $imageThumbModel->save();

            $thatDesignResult->share_img_girl_id = $imageThumbModel->id;
            $thatDesignResult->save();

            $shareImgUrl = FileManager::getLocalFile($imageThumbModel->id);

            $imgInfo['girl']["img_url"] = $shareImgUrl;
            $imgInfo['girl']['img_id']  = $imageThumbModel->id;
        }

        return response()->json(['level'=>'success','message'=>'生成成功','data'=>$imgInfo]);
    }

    public function getActiveStatus(Request $request){

        $code = $request->get('code');

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'请先登录','data'=>'no_login']);

        /** @var DesignResult $thatDesignResult */
        $thatDesignResult = DesignResult::whereKey($code)->first();

        if(!$thatDesignResult)
            return response()->json(['level'=>'error','message'=>'页面找不到或不允许访问！','data'=>'']);

        $result['support_num'] = $thatDesignResult->support_num;

        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereNote($code)->first();
        if(!$thatOrder)
            return response()->json(['level'=>'error','message'=>'订单不存在！','data'=>'']);

        if($thatOrder->pay_type == "free"){
            if((int)$result['support_num'] >= 20){
                if($thatOrder->ispay == 1){
                    $timeInit = 0;
                    if(self::isActiveAction()){
                        $timeInit = strtotime(env("ACTIVE_END_TIME")) - time();
                    }
                    $result["time_init"] = $timeInit;
                    $result["is_action"] = 1;
                    $result['is_pay']    = 1;
                    $result["pay_type"]  = "free";
                }else{
                    $thatOrder->s_amount = round((float)$thatOrder->s_amount * 0.6,2);
                    $thatOrder->pay_type = "wxpay_6";
                    $thatOrder->save();

                    $result["time_init"] = 0;
                    $result["is_action"] = 1;
                    $result['is_pay']    = 0;
                    $result["pay_type"]  = "wxpay_6";
                }
            }else{
                if(self::isActiveAction()){
                    $result["time_init"] = strtotime(env("ACTIVE_END_TIME")) - time();
                    $result["is_action"] = 1;
                    $result['is_pay']    = 0;
                    $result["pay_type"]  = "free";
                }else{
                    $result["time_init"] = 0;
                    $result["is_action"] = 0;
                    $result['is_pay']    = 0;
                    $result["pay_type"]  = "wxpay";
                }
            }

        }else{
            if($thatOrder->ispay == 0){
                $result["time_init"] = self::isActiveAction() ? strtotime(env("ACTIVE_END_TIME")) - time() :0;
                $result["is_action"] = self::isActiveAction() ? 1 : 0;
                $result['is_pay']    = 0;
                $result["pay_type"]  = $thatOrder->pay_type;
            }else{
                $result["time_init"] = self::isActiveAction() ? strtotime(env("ACTIVE_END_TIME")) - time() :0;
                $result["is_action"] = self::isActiveAction() ? 1 : 0;
                $result['is_pay']    = 1;
                $result["pay_type"]  = "wxpay";
            }
        }

        $result['order_num'] = $thatOrder->order_num;

        return response()->json(['level'=>'success','message'=>'获取成功',"data"=>$result]);
    }

    public function testBuildTshirt(Request $request){
        $designId = $request->get('d_id');
        $materialId = $request->get('m_id');

        $thatDesign = Design::whereId($designId)->first();
        $thatMaterial = Material::whereImgId($materialId)->first();

        $aa = self::saveTShirtEffect($thatDesign,$thatMaterial);

        return response()->json(["url"=>FileManager::getAliOssFile($aa->id)]);
    }

    public static function saveTShirtEffect(Design $design,Material $material){

        if(!$design)
            return false;

        if(!$material)
            return false;

        $thatDesignImage   = Images::whereId($design->img_id)->first();

        $thatMaterialImage = Images::whereId($material->img_id)->first();

        if(!$thatDesignImage)
            return false;

        if(!$thatMaterialImage)
            return false;

        /** @var Files $thatDesignFile */
        $thatDesignFile   = $thatDesignImage->files;
        $thatMaterialFile = $thatMaterialImage->files;
        if(!$thatDesignFile || !$thatMaterialFile)
            return false;

        $thatDesignContent   = $thatDesignFile->getContent();
        $thatMaterialContent = $thatMaterialFile->getContent();

        $designInfo   = Image::make($thatDesignContent);
        $materialInfo = Image::make($thatMaterialContent);
        $designInfo->insert($materialInfo, 'top', 192, 102)->encode($thatDesignFile->file_ext);
        /** @var Files $fileResult */
        $fileResult = FileManager::saveFileByFileContent($designInfo->encoded, $thatDesignFile->file_name . '-T-shirt' . $thatDesignFile->file_type, $designInfo->mime());

        $imageModel = new Images();
        $imageModel->files()->associate($fileResult);
        $imageModel->img_type = $thatDesignFile->file_type;
        $imageModel->img_name = $thatDesignFile->file_name . '-T-shirt';
        $imageModel->save();

        return $imageModel;
    }

    public function isInActive(Request $request){
        if(self::isActiveAction()){
            $info["time_init"] = strtotime(env("ACTIVE_END_TIME")) - time();
            $info["is_action"] = 1;
        }else{
            $info["time_init"] = 0;
            $info["is_action"] = 0;
        }

        return response()->json(['level'=>'success','message'=>'获取成功',"data"=>$info]);
    }

    public static function isActiveAction(){
        $startTime = env("ACTIVE_START_TIME");
        $endTime   = env("ACTIVE_END_TIME");

        $allFreeOrderCount = Orders::wherePayType('free')->whereIspay(1)->count();
        if($allFreeOrderCount < 20 && time() > strtotime($startTime) && time() < strtotime($endTime)){
            return true;
        }else{
            return false;
        }
    }

    public function setRewardFollow(Request $request){
        $rrId = $request->get('rr_id');
        $num  = $request->get('num');

        for($i = 0; $i<(int)$num;$i++){
            $newRewardFollow = new RewardFollow();
            $newRewardFollow->rr_id = $rrId;
            $newRewardFollow->status = 1;
            $newRewardFollow->save();
        }

        echo "complete";
    }

    public function sendExpressSms(Request $request){
        $phone=$request->get('phone');
        $num  = $request->get('num');

        $send = new YunPian();
        $a=$send->sendExpressSms($phone,$num);

        var_dump($a);
    }
}